package com.winning.pmph.schedule;

import com.alibaba.fastjson.JSON;
import com.winning.pmph.entity.*;
import com.winning.pmph.service.ExerciseBookService;
import com.winning.pmph.service.ExerciseEntryService;
import com.winning.pmph.service.ExerciseGroupLibService;
import com.winning.pmph.service.ExerciseGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@ConditionalOnProperty(prefix = "scheduling", name = "enabled")
public class ExerciseLibSchedule {
    @Resource
    private ExerciseBookService exerciseBookService;
    @Resource
    private ExerciseGroupService exerciseGroupService;
    @Resource
    private ExerciseEntryService exerciseEntryService;
    @Resource
    private ExerciseGroupLibService exerciseGroupLibService;

    @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨两点启动定时任务
//    @Scheduled(cron = "0 0 1 ? * 7 *") // 每周六凌晨一点;
    public void publishExerciseGroup(){
        log.info("启动定时任务, 上周发布试题图书, 入试题库, 并校验相似性;");
        List<ExerciseBook> exerciseBookList = exerciseBookService.lambdaQuery()
                .eq(ExerciseBook::getStatus, ExerciseBook.BOOK_STATUS_PUBLISHED)
                .eq(ExerciseBook::getVersion, 1)
                .gt(ExerciseBook::getUpdatedTime, LocalDate.now().plusDays(-1)).list();
        List<ExerciseGroup> exerciseGroupList = exerciseGroupService.lambdaQuery().in(ExerciseGroup::getExerciseBookId, exerciseBookList.stream().map(ExerciseBook::getId).collect(Collectors.toList())).list();
        for (ExerciseGroup exerciseGroup : exerciseGroupList) {
            ExerciseGroupLib exerciseGroupLib = JSON.parseObject(JSON.toJSONString(exerciseGroup), ExerciseGroupLib.class);
            exerciseGroupLib.setExerciseEntryList(exerciseEntryService.lambdaQuery().eq(ExerciseEntry::getGroupId, exerciseGroup.getId()).list());
            exerciseGroupLibService.saveOrUpdateExerciseGroupLib(exerciseGroupLib);
        }
        log.info("试题图书定时任务结束;");
    }
}
